# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
import re
from pymysql.pymysql import DB
from interface_test import parse_txt, get_zt_project


def api_import():
    product_id = ''
    api_id = ''
    for i in parse_txt('config', 'product_module_list.conf'):
        if not i == '\n':
            i = i.replace('\n', '')
            product = {}
            if (i.find('[') and i.find(']')) == 0:
                p = i.lstrip('[').rstrip(']')
                ps = p.split(',')
                for ii in ps:
                    k, v = ii.split('=')
                    product[k] = v
                DB('db0').Table('product').Insert({'zt_product_id': product['zt_id'], 'name': product['product_name'],
                                                   'description': product['description']})
                product_id = DB('db0').GetLastInsertId()
                projects = get_zt_project('11')
                for p in projects:
                    DB('db0').Table('project').Insert(
                        {'product_id': product_id, 'name': p['code'], 'description': p['name']})
            else:
                api_json = eval(
                    requests.get('http://doc.hfjy.red/content.html?type=C&name=' + i + '&outType=json').text)
                for ii in api_json['actionList']:
                    uri = re.findall(r"https://xue-dev.hfjy.com(.+?)" + ii['actionName'],
                                     ii['call_sample'].replace('\\', ''))[0]
                    DB('db0').Table('api').Insert(
                        {'product_id': product_id, 'name': ii['actionName'], 'uri': uri, 'description': ii['memo'], })
                    api_id = DB('db0').GetLastInsertId()
                    if ii['parms']:
                        for p in ii['parms']:
                            DB('db0').Table('api_args').Insert(
                                {'api_id': api_id, 'args_name': p['name'], 'data_type': p['type'],
                                 'check_type': p['checkType'], 'check_value': p['checkValue'],
                                 'note': p['memo']})
                    if ii['returns']:
                        for rt in ii['returns']:
                            DB('db0').Table('api_response').Insert(
                                {'api_id': api_id, 'field': rt['name'], 'data_type': rt['type'],
                                 'description': rt['memo']})
                    if ii['codes']:
                        for c in ii['codes']:
                            DB('db0').Table('api_response_code').Insert(
                                {'api_id': api_id, 'code': c['code'], 'description': c['memo']})
